package net.siit.ling;

import edu.stanford.nlp.ling.Sentence;
import edu.stanford.nlp.ling.TaggedWord;
import edu.stanford.nlp.ling.Word;
import edu.stanford.nlp.tagger.maxent.*;

import java.net.URL;
import java.util.*;
import net.siit.datatype.AnnotatedRange;

/**
 *
 * @author arthit
 */
public class POSTagger {
    private MaxentTagger tagger;
    private ThaiSeg tokenizer;
    private URL modelURL;
    
    public POSTagger() throws Exception {
        setModelURL(this.getClass().getResource("/siit/tagger/thai.tagger"));
        tokenizer = new ThaiSeg();
    }
    
    public POSTagger(URL modelURL) throws Exception {
        setModelURL(modelURL);
        tokenizer = new ThaiSeg();
    }

    public void setModelURL(URL url) throws Exception {
        modelURL = url;
        tagger = new MaxentTagger(modelURL.getFile());
    }
    
    public URL getModelURL() {
        return modelURL;
    }

    public List<Sentence> tag(List<Sentence> sentences) {
        return tagger.process(sentences);
    }
    
    public Sentence<TaggedWord> tag(Sentence sentence) {
        return tagger.processSentence(sentence);
    }

    public Sentence<TaggedWord> tag(String[] tokens) {
        Sentence<Word> ts = new Sentence<Word>();
        
        for (String token : tokens) {
            ts.add(new Word(token));
        }
        
        return tagger.processSentence(ts);
    }
    
    public Sentence<TaggedWord> tag(String text) {
        Sentence<Word> ts = new Sentence<Word>();

        List<AnnotatedRange<Integer>> tokens
                = tokenizer.tokenizeLongestMatch(text);
        
        //System.err.println("tokens = " + tokens.size());
        for (AnnotatedRange<Integer> token : tokens) {
            ts.add(new Word(text.substring(token.getStart(), token.getEnd())));
        }

        return tagger.processSentence(ts);
    }

    public static void main (String[] args) {
        POSTagger tagger = null;
        try {
            tagger = new POSTagger();
        } catch (Exception ex) {
            ex.printStackTrace();
            System.err.println("Can't create tagger.");
            System.exit(1);
        }

        Sentence<TaggedWord> ts = tagger.tag(args[0]);

        System.out.println("words = " + ts.length());
        
        for (TaggedWord word : ts) {
            System.out.print(word.word() + "/" + word.tag() + " ");
        }
    }
}